<template>
  <div class="userbalance">
    <h3>修改用户余额</h3>
    <el-divider></el-divider>
    <el-form label-position="left" label-width="80px" :model="userBalance">
      <el-form-item label="用户名">
        <el-input v-model="userBalance.yhm" @blur="selectUserYue" v-loading="loadingflag" placeholder="请输入用户名">
          <template slot="append">用户当前余额：{{useryue}}</template>
        </el-input>
      </el-form-item>
      <el-form-item label="金额">
        <el-input v-model="userBalance.yue" placeholder="请输入+(-)金额"></el-input>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="userBalance.remarks" placeholder="操作备注"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="editBalance" :loading="loading">修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import qs from "qs";
import {getUserBalance, setUserBalance} from "../../utils/api";

export default {
  name: "UserBalance",
  data(){
    return {
      userBalance:{
        yhm:'',
        yue:'',
        remarks:''
      },
      loading:false,
      useryue:0,
      loadingflag:false,
    }
  },
  created() {
    let {user} = this.$route.query
    if(user){
      this.userBalance.yhm = user
      this.selectUserYue()
    }
  },
  methods:{
    editBalance(){
      this.loading=true;
      setUserBalance(qs.stringify({username:this.userBalance.yhm,yue:this.userBalance.yue,remarks:this.userBalance.remarks || undefined})
      ).then(respose=>{
        if(respose.status===200){
          this.useryue=(this.useryue-0)+(this.userBalance.yue-0);
          this.$message({
            message: '修改成功',
            type: 'success'
          });
          this.loading=false;
        }else {
          this.$message.error('修改失败，请稍后再试');
          this.loading=false;
        }
      }).catch(error=>{
        console.log(error);
      })
    },
    selectUserYue(){
      if(this.userBalance.yhm.trim()!==""){
        this.loadingflag=true;
        getUserBalance(qs.stringify({username:this.userBalance.yhm})
        ).then(respose=>{
          this.loadingflag=false;
          if(respose.status===200){
            this.useryue=respose.body;
          }else {
            this.loadingflag=false;
            this.$message.error('用户名错误，请检查');
          }
        }).catch(error=>{
          this.loadingflag=false;
          console.log(error);
          this.$message.error('未知错误，请联系管理员');
        })
      }else{
        this.useryue=0
      }
    }
  }
}
</script>

<style scoped>

</style>
